package com.cngphone.AnFetion;

import java.util.ArrayList;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.cngphone.AnFetion.Fetion.FetionMessageProvider;
import com.cngphone.AnFetion.Fetion.SIPC.ReserveNotify;
import com.cngphone.AnFetion.FetionMessage.MessageStatus;
import com.cngphone.AnFetion.tools.LogUtil;
import com.cngphone.AnFetion.tools.StrUtil;
import com.cngphone.AnFetion2.R;

public class SendSMSActivity extends Activity implements IFriendInfoChanged {

	public class MessageAdapter extends BaseAdapter {
		private Activity context;
		
		public MessageAdapter(final Activity context) {
			this.context = context;
		}
		@Override
		public int getCount() {
			if (fetionFriend == null)
				return 0;
			return fetionFriend.getMessage().size(); 
		}

		@Override
		public Object getItem(int position) {
			if (fetionFriend == null)
				return null;
			if (fetionFriend.getMessage().size() <= position)
				return null;
			return fetionFriend.getMessage().get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView view = (TextView)convertView;
			if (fetionFriend == null)
				return null;
			FetionMessage message = (FetionMessage)getItem(position);
			if (message == null)
				return null;
			if (view == null) {
				view = new TextView(context);
				view.setTextSize(16);
				view.setPadding(10, 3, 10, 3);
				view.setTextColor(Color.BLACK);
			}
			if (message.getSender() != null && message.getSender().isMe)
				view.setBackgroundResource(R.color.SelfMessageBackground);
			else
				view.setBackgroundResource(R.color.FriendMessageBackground);
			view.setText(message.toString());
			return view;
		}

	}

	private static final int MENU_CLOSE = Menu.FIRST + 1;
	private static final int MENU_SHOW_MSG = MENU_CLOSE + 1;

	private static final String TAG = "SendSMSActivity";

	private static FetionService mBoundService;
	private String uri;
	private FetionFriend fetionFriend;

	private EditText editOriginalContent;
	private NewEditText editContent;
	private Button sendButton;
	private ListView messageList;

	public FetionFriend getFetionFriend() {
		return fetionFriend;
	}

	private ServiceConnection mConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			mBoundService = ((FetionService.LocalBinder) service).getService();

			FetionService.chatActivity = SendSMSActivity.this;

			// fetionFriend = (FetionFriend)
			// SendSMSActivity.this.getIntent().getSerializableExtra("friend");
			updateIntent();

			sendButton.setOnClickListener(new SendSMSClickListener());
			// findViewById(R.id.buttoncancel).setOnClickListener(new
			// OnClickListener() {
			// @Override
			// public void onClick(View arg0) {
			// SendSMSActivity.this.finish();
			// }
			//
			// });
			editContent.setOnKeyListener(new OnKeyListener() {

				@Override
				public boolean onKey(View arg0, int arg1, KeyEvent keyCode) {
					// System.out.println(keyCode.getKeyCode() + ":" + arg1 +
					// ":" +
					// keyCode.isShiftPressed());
					if (keyCode.getAction() == KeyEvent.ACTION_DOWN
							&& !keyCode.isShiftPressed()
							&& !keyCode.isAltPressed()
							&& keyCode.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
						sendButton.performClick();
						return true;
					}
					return false;
				}

			});
			// sendButton.setHeight(editContent.getHeight());

			ReserveNotify notify = mBoundService.getReserveNotify();
			if (notify != null)
				notify.addFriendInfoChangedListener(SendSMSActivity.this);
		}

		@Override
		public void onServiceDisconnected(ComponentName className) {
			FetionService.chatActivity = null;
			mBoundService = null;
		}
	};

	@Override
	protected void onNewIntent(Intent intent) {
		setIntent(intent);
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mBoundService == null)
			return;
		ReserveNotify notify = mBoundService.getReserveNotify();
		if (notify != null)
			notify.removeFriendInfoChangedListener(SendSMSActivity.this);
		FetionService.chatActivity = null;
	}

	@Override
	protected void onResume() {
		super.onResume();
		// System.out.println(findViewById(R.id.btnlayout).getMeasuredHeight() +
		// ":"+editContent.getMeasuredHeight()+ ":" +
		// sendButton.getMeasuredHeight());

		if (mBoundService == null)
			return;
		FetionService.chatActivity = this;
		ReserveNotify notify = mBoundService.getReserveNotify();
		if (notify != null)
			notify.addFriendInfoChangedListener(SendSMSActivity.this);
		updateIntent();
	}

	protected void updateIntent() {
		uri = getIntent().getStringExtra("uri");
		ArrayList<FetionFriend> buddies = mBoundService.getFriendManager()
				.getBuddies();
		fetionFriend = mBoundService.getFriendManager().getFriend(uri);

		((TextView) findViewById(R.id.origin_title)).setText(fetionFriend
				.toShortString());

		mBoundService.getFriendManager().beginChat(fetionFriend);

		addMessage(TextUtils.join("\n", fetionFriend.getMessage()) + "\n", false);
		mBoundService.getFriendManager().removeMessageNotify(fetionFriend);
		messageList.invalidateViews();
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.sendsms);
		editOriginalContent = (EditText) findViewById(R.id.originalcontent);
		messageList = (ListView) findViewById(R.id.listmessage);
		messageList.setAdapter(new MessageAdapter(this));
		editContent = (NewEditText) findViewById(R.id.content);
		sendButton = (Button) findViewById(R.id.buttonsend);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.custom_title);

		// 绑定服务
		this.bindService(MiscUtil.getFetionServiceIntent(this), mConnection,
				Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onDestroy() {
		// mBoundService.setlastReceivedMessage(null); //Tiger. Add
		// if (mBoundService.getFetionListFriends() == null) {
		// startActivity(MiscUtil.getHome(this));
		// }
		unbindService(mConnection);
		super.onDestroy();
	}

	private void addMessage(String s, boolean isAppend) {
		if (isAppend) {
			editOriginalContent.getEditableText().append(s).append("\n");
		} else {
			editOriginalContent.setText(s);
		}
		editOriginalContent.setSelection(editOriginalContent.length());
		editContent.requestFocus();
	}

	public void onReceiveMessage() {
		runOnUiThread(new Runnable() {
			public void run() {
				addMessage(TextUtils.join("\n", fetionFriend.getMessage()) + "\n", false);
				messageList.invalidateViews();
			}
		});
	}

	protected static int SMSSerial = 1;
	protected static int FetionIMSerial = -1;

	protected class SendSMSClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {

			try {
				if (!MiscUtil.checkIsOnline())
					return;
				final String content = editContent.getText().toString();
				new Handler().post(new Runnable() {
					@Override
					public void run() {
						if (content.length() == 0)
							return;

						mBoundService.saveMessage(StrUtil
								.getPeopleId(mBoundService.getMyself().Uri),
								StrUtil.getPeopleId(fetionFriend.Uri), content);

						// 好友离线时发送失败判断有误，暂时去掉
						// if(mBoundService.sendSMS(uri, context))
						int status = mBoundService.sendSMS(uri, content);

						String msg;
						FetionMessage.MessageStatus result;
						if (status == 200) {
							result = MessageStatus.Normal;
						} else if (status == 280) {
							result = MessageStatus.Sms;
						} else {
							result = MessageStatus.Failed;
							editContent.setText(content);
						}
						msg = fetionFriend.addMessage(new FetionMessage(
								mBoundService.getMyself(), content, result));

						if (Settings.DEBUG)
							LogUtil.d(TAG, msg);

						addMessage(msg, true);
						messageList.invalidateViews();
					}
				});
				editContent.setText("");
			} finally {
				editContent.requestFocus();

			}
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0, MENU_CLOSE, 0, "结束聊天");
		menu.add(0, MENU_SHOW_MSG, 1, "查看好友历史消息");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case (MENU_CLOSE): {
			mBoundService.getFriendManager().endChat(fetionFriend);
			fetionFriend.getMessage().clear();
			finish();
			break;
		}
		case (MENU_SHOW_MSG): {
			String peopleId = StrUtil.getPeopleId(fetionFriend.Uri);

			Uri uri = Uri.parse(FetionMessageProvider.Fetion.CONTENT_URI
					+ "/people/" + peopleId);
			LogUtil.v(TAG, "start activity with data : " + uri.toString());

			Intent intent = new Intent(FetionMessageHistory.SHOW_MSGS_WHO);
			intent.setData(uri);
			// TODO just a temp solution. do later run-time binding
			intent
					.setClass(getApplicationContext(),
							FetionMessageHistory.class);
			startActivity(intent);
			break;
		}
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void Happened(FetionFriend friend) {
		if (friend != fetionFriend)
			return;
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				((TextView) findViewById(R.id.origin_title))
						.setText(fetionFriend.toShortString());
				messageList.invalidateViews();
			}

		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
		}
		return false;
	}

}
